package main

import (
	"code/pb"
	"fmt"
	"log"
	"net"
	"time"

	"google.golang.org/grpc"
)

type server struct {
	pb.UnimplementedQueryServer
}

func (s *server) Watch(req *pb.Request, stream pb.Query_WatchServer) error {
	log.Printf("server receive Watch request, role=%s", req.Role)
	id := 0
	var err error
	for {
		info := fmt.Sprintf("response id=%d", id)
		resp := &pb.Response{Info: info}
		if err = stream.Send(resp); err != nil {
			log.Printf("send error, err=%v", err)
			break
		}
		log.Printf("send success, info id=%d", id)
		id += 1
		time.Sleep(time.Minute)
	}
	return err
}

func main() {
	lis, err := net.Listen("tcp", ":7000")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterQueryServer(s, &server{})
	log.Println("Server started, listening on port 7000")
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
